const { db } = require('../db/index');
const jwt = require('jsonwebtoken')
const config = require('../config')


module.exports = login = (req, res) => {
    const userInfo = req.body;
    // db.connect();

    const sql1 = `select * from user where username=?`;
    db.query(sql1, [userInfo.username], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        if (results.length === 0) {
            return res.cc('登录失败, 请检查用户名是否输入正确');
        }
        if (results[0].password === userInfo.password) {

            // 生成token字符串
            let user = { ...results[0], password: '', gender: '' }
            // console.log(user)
            // 进行加密，生产token字符串
            const tokenStr = jwt.sign(user, config.jwtSecretKey,{expiresIn:config.expiresIn})

            return res.send({
                status: 0,
                message: '登录成功',
                token: 'Bearer '+tokenStr
            });
        } else {
            res.cc('用户名或密码错误');
        }
    });
    // db.end()
};
